import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import '../services/http_service.dart';
import '../services/gitcode_api_service.dart';
import 'settings_page.dart';
import 'repository_list_page.dart';
import 'user_info_page.dart';

/// 主页面 - GitCode 口袋工具
class HomePage extends StatefulWidget {
  final HttpService httpService;
  final GitCodeApiService apiService;
  
  const HomePage({
    super.key,
    required this.httpService,
    required this.apiService,
  });
  
  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _selectedIndex = 0;
  Map<String, dynamic>? _userInfo;
  bool _isLoading = false;
  String? _errorMessage;
  CancelToken? _cancelToken;
  
  @override
  void initState() {
    super.initState();
    _checkTokenAndLoadUser();
  }
  
  @override
  void dispose() {
    _cancelToken?.cancel('页面销毁');
    super.dispose();
  }
  
  /// 检查 token 并加载用户信息
  Future<void> _checkTokenAndLoadUser() async {
    final token = widget.httpService.accessToken;
    if (token == null || token.isEmpty) {
      setState(() {
        _errorMessage = '请先配置 Personal Access Token';
      });
      return;
    }
    
    await _loadUserInfo();
  }
  
  /// 加载用户信息
  Future<void> _loadUserInfo() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });
    
    _cancelToken?.cancel('新请求');
    _cancelToken = CancelToken();
    
    try {
      final userInfo = await widget.apiService.getCurrentUser(
        cancelToken: _cancelToken,
      );
      setState(() {
        _userInfo = userInfo;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        if (e is HttpException) {
          if (e.statusCode == 401) {
            _errorMessage = 'Token 无效，请检查设置';
          } else {
            _errorMessage = '错误: ${e.message}';
          }
        } else {
          _errorMessage = '加载失败: $e';
        }
      });
    }
  }
  
  /// 导航到设置页面
  void _navigateToSettings() async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => SettingsPage(
          httpService: widget.httpService,
        ),
      ),
    );
    
    // 从设置页面返回后，重新加载用户信息
    if (result == true || mounted) {
      _checkTokenAndLoadUser();
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('GitCode 口袋工具'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        actions: [
          IconButton(
            icon: const Icon(Icons.settings),
            onPressed: _navigateToSettings,
            tooltip: '设置',
          ),
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _loadUserInfo,
            tooltip: '刷新',
          ),
        ],
      ),
      body: _buildBody(),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _selectedIndex,
        onTap: (index) {
          setState(() {
            _selectedIndex = index;
          });
        },
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.person),
            label: '我的信息',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.folder),
            label: '我的仓库',
          ),
        ],
      ),
    );
  }
  
  Widget _buildBody() {
    if (_selectedIndex == 0) {
      return UserInfoPage(
        userInfo: _userInfo,
        isLoading: _isLoading,
        errorMessage: _errorMessage,
        onRefresh: _loadUserInfo,
      );
    } else {
      return RepositoryListPage(
        apiService: widget.apiService,
        httpService: widget.httpService,
      );
    }
  }
}

